package clam.apps.adu.metier;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class Story
{
	private static final String	TAG_ID				= "id";
	private static final String	TAG_TEXTE			= "texte";
	private static final String	TAG_DATE			= "date";
	private static final String	TAG_LOGIN			= "login";
	private static final String	TAG_PHOTO			= "photo";
	private static final String	TAG_NBPLUS			= "nbPlus";
	private static final String	TAG_NBMOINS			= "nbMoins";
	private static final String	TAG_ETAT			= "etat";
	private static final String	TAG_THEME			= "theme";
	private static final String	TAG_ETABLISSEMENT	= "etablissement";
	private static final String	TAG_DEPARTEMENT		= "departement";
	private int					id;
	private String				texte;
	private Date				date;
	private String				login;
	private String				photo;
	private int					nbplus;
	private int					nbmoins;
	private Etat				etat;
	private Theme				theme;
	private Etablissement		etablissement;
	private Departement			departement;
	
	public Story()
	{
		this.etat = new Etat();
		this.theme = new Theme();
		this.etablissement = new Etablissement();
		this.departement = new Departement();
		this.date = new Date();
		this.login = "Anonyme";
		this.photo = "aucune";
		this.nbplus = 0;
		this.nbmoins = 0;
	}
	
	/*
	 * (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString()
	{
		return "Story [id=" + this.id + ", texte=" + this.texte + ", date="
				+ this.date + ", login=" + this.login + ", photo=" + this.photo
				+ ", nbplus=" + this.nbplus + ", nbmoins=" + this.nbmoins
				+ ", etat=" + this.etat.toString() + ", theme="
				+ this.theme.toString() + ", etablissement="
				+ this.etablissement.toString() + ", departement="
				+ this.departement.toString() + "]";
	}
	
	public void ajouter()
	{
		this.ajouterImage();
		
		HttpClient httpclient = new DefaultHttpClient();
		String depa;
		if (this.departement != null)
			depa = "/" + this.departement.getId();
		else
			depa = "";
		String url = ParserJsonJavaManager.URL_AJOUTER_STORY + this.login + "/"
				+ this.texte + "/" + this.photo + "/" + this.etat.getId() + "/"
				+ this.theme.getId() + "/" + this.etablissement.getId() + depa;
		
		url = url.replace(" ", "%20");
		
		Log.i("URL", url);
		HttpPost httppost = new HttpPost(url);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+05:00"));
		
		HttpResponse response;
		
		try
		{
			response = httpclient.execute(httppost); // On effectue la requete
			Log.i("REPONSE STORY", EntityUtils.toString(response.getEntity()));
		}
		catch (ClientProtocolException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void ajouterImage()
	{
		HttpURLConnection connection = null;
		DataOutputStream outputStream = null;
		
		String urlServer = ParserJsonJavaManager.URL_AJOUTER_IMAGE;
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		
		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1 * 1024 * 1024;
		
		Log.i("AJOUTER IMAGE", "DEBUT");
		
		try
		{
			FileInputStream fileInputStream = new FileInputStream(new File(
					this.photo));
			
			URL url = new URL(urlServer);
			
			connection = (HttpURLConnection) url.openConnection();
			Log.i("URL IMAGE", urlServer);
			// Allow Inputs & Outputs
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			
			// Enable POST method
			connection.setRequestMethod("GET");
			
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			
			outputStream = new DataOutputStream(connection.getOutputStream());
			outputStream.writeBytes(twoHyphens + boundary + lineEnd);
			outputStream
					.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
							+ this.photo + "\"" + lineEnd);
			outputStream.writeBytes(lineEnd);
			
			bytesAvailable = fileInputStream.available();
			bufferSize = Math.min(bytesAvailable, maxBufferSize);
			buffer = new byte[bufferSize];
			
			// Read file
			bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			
			while (bytesRead > 0)
			{
				outputStream.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}
			
			outputStream.writeBytes(lineEnd);
			outputStream.writeBytes(twoHyphens + boundary + twoHyphens
					+ lineEnd);
			
			fileInputStream.close();
			outputStream.flush();
			outputStream.close();
		}
		catch (Exception ex)
		{	
			
		}
	}
	
	public static ArrayList<Story> findAll()
	{
		
		ParserJsonJavaManager pjjm = new ParserJsonJavaManager();
		
		return pjjm.findStorysList(ParserJsonJavaManager.URL_FIND_ALL_STORYS);
	}
	
	public static Story findByLibelle(int $id)
	{
		ParserJsonJavaManager pjjm = new ParserJsonJavaManager();
		
		return pjjm.findStoryById($id);
	}
	
	public static ArrayList<Story> findByTheme(String libelle_theme,
			String libelle_etat)
	{
		ParserJsonJavaManager pjjm = new ParserJsonJavaManager();
		
		return pjjm
				.findStorysList(ParserJsonJavaManager.URL_FIND_STORYS_BY_THEME
						+ libelle_theme + "/" + libelle_etat);
	}
	
	public static ArrayList<Story> findByEtat(String libelle_etat)
	{
		ParserJsonJavaManager pjjm = new ParserJsonJavaManager();
		
		return pjjm
				.findStorysList(ParserJsonJavaManager.URL_FIND_STORYS_BY_ETAT
						+ libelle_etat);
	}
	
	public static ArrayList<Story> findBySite(String libelle_site,
			String libelle_etat)
	{
		ParserJsonJavaManager pjjm = new ParserJsonJavaManager();
		
		return pjjm
				.findStorysList(ParserJsonJavaManager.URL_FIND_STORYS_BY_THEME
						+ libelle_site + "/" + libelle_etat);
	}
	
	public static ArrayList<Story> findByEtablissement(
			String libelle_etablissement, String libelle_etat)
	{
		ParserJsonJavaManager pjjm = new ParserJsonJavaManager();
		
		return pjjm
				.findStorysList(ParserJsonJavaManager.URL_FIND_STORYS_BY_ETABLISSEMENT
						+ libelle_etablissement + "/" + libelle_etat);
	}
	
	public static ArrayList<Story> findByDepartement(
			String libelle_departement, String libelle_etat)
	{
		ParserJsonJavaManager pjjm = new ParserJsonJavaManager();
		
		return pjjm
				.findStorysList(ParserJsonJavaManager.URL_FIND_STORYS_BY_DEPARTEMENT
						+ libelle_departement + "/" + libelle_etat);
	}
	
	public static ArrayList<Story> findByLogin(String login, String libelle_etat)
	{
		ParserJsonJavaManager pjjm = new ParserJsonJavaManager();
		
		return pjjm
				.findStorysList(ParserJsonJavaManager.URL_FIND_STORYS_BY_LOGIN
						+ login + "/" + libelle_etat);
	}
	
	public boolean votePlus()
	{
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(
				ParserJsonJavaManager.URL_VOTE_PLUS_STORY + this.getId()); // On
																			// se
																			// connecte
		
		HttpResponse response;
		try
		{
			response = httpclient.execute(httppost); // On effectue la requete
			return (EntityUtils.toString(response.getEntity()) == "OK") ? true
					: false;
		}
		catch (ClientProtocolException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}
	
	public boolean voteMoins()
	{
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(
				ParserJsonJavaManager.URL_VOTE_MOINS_STORY + this.getId()); // On
																			// se
																			// connecte
		
		HttpResponse response;
		try
		{
			response = httpclient.execute(httppost); // On effectue la requete
			return (EntityUtils.toString(response.getEntity()) == "OK") ? true
					: false;
		}
		catch (ClientProtocolException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}
	
	public int getId()
	{
		return this.id;
	}
	
	public void setId(Integer id)
	{
		this.id = id;
	}
	
	public String getTexte()
	{
		return this.texte;
	}
	
	public void setTexte(String texte)
	{
		this.texte = texte;
	}
	
	public Date getDate()
	{
		return this.date;
	}
	
	public void setDate(Date date)
	{
		this.date = date;
	}
	
	public String getLogin()
	{
		return this.login;
	}
	
	public void setLogin(String login)
	{
		this.login = login;
	}
	
	public String getPhoto()
	{
		return this.photo.replace("@2", "/");
	}
	
	public void setPhoto(String photo)
	{
		photo = photo.replace("/", "@2");
		this.photo = photo;
	}
	
	public int getNbplus()
	{
		return this.nbplus;
	}
	
	public void setNbplus(Integer nbPlus)
	{
		this.nbplus = nbPlus;
	}
	
	public int getNbmoins()
	{
		return this.nbmoins;
	}
	
	public void setNbmoins(Integer nbMoins)
	{
		this.nbmoins = nbMoins;
	}
	
	public Etat getEtat()
	{
		return this.etat;
	}
	
	public Theme getTheme()
	{
		return this.theme;
	}
	
	public Etablissement getEtablissement()
	{
		return this.etablissement;
	}
	
	public Departement getDepartement()
	{
		return this.departement;
	}
	
	/**
	 * @return the tagId
	 */
	public static String getTagId()
	{
		return Story.TAG_ID;
	}
	
	/**
	 * @return the tagTexte
	 */
	public static String getTagTexte()
	{
		return Story.TAG_TEXTE;
	}
	
	/**
	 * @return the tagDate
	 */
	public static String getTagDate()
	{
		return Story.TAG_DATE;
	}
	
	/**
	 * @return the tagLogin
	 */
	public static String getTagLogin()
	{
		return Story.TAG_LOGIN;
	}
	
	/**
	 * @return the tagPhoto
	 */
	public static String getTagPhoto()
	{
		return Story.TAG_PHOTO;
	}
	
	/**
	 * @return the tagNbplus
	 */
	public static String getTagNbplus()
	{
		return Story.TAG_NBPLUS;
	}
	
	/**
	 * @return the tagNbmoins
	 */
	public static String getTagNbmoins()
	{
		return Story.TAG_NBMOINS;
	}
	
	/**
	 * @return the tagEtat
	 */
	public static String getTagEtat()
	{
		return Story.TAG_ETAT;
	}
	
	/**
	 * @return the tagTheme
	 */
	public static String getTagTheme()
	{
		return Story.TAG_THEME;
	}
	
	/**
	 * @return the tagEtablissement
	 */
	public static String getTagEtablissement()
	{
		return Story.TAG_ETABLISSEMENT;
	}
	
	/**
	 * @return the tagDepartement
	 */
	public static String getTagDepartement()
	{
		return Story.TAG_DEPARTEMENT;
	}
	
	/**
	 * @param etat
	 *            the etat to set
	 */
	public void setEtat(Etat etat)
	{
		this.etat = etat;
	}
	
	/**
	 * @param theme
	 *            the theme to set
	 */
	public void setTheme(Theme theme)
	{
		this.theme = theme;
	}
	
	/**
	 * @param etablissement
	 *            the etablissement to set
	 */
	public void setEtablissement(Etablissement etablissement)
	{
		this.etablissement = etablissement;
	}
	
	/**
	 * @param departement
	 *            the departement to set
	 */
	public void setDepartement(Departement departement)
	{
		this.departement = departement;
	}
}
